import 'dart:math';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';

import '../../generated/l10n.dart';
import '../../model/msg_entity.dart';
import '../dao/diary_dao.dart';
import '../model/diary_entity.dart';

class DiaryAdd extends StatefulWidget {
  const DiaryAdd({super.key});
  @override
  State<DiaryAdd> createState() => _DiaryAddState();
}

class _DiaryAddState extends State<DiaryAdd> {
  DiaryModel _diaryModel = DiaryModel();
  String diaryDate = "";
  DateTime? selectedDay;
  int? diaryId;

  final TextEditingController _titleController = TextEditingController()
    ..text = '';
  final TextEditingController _contentController = TextEditingController()
    ..text = '';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Object? arguments = ModalRoute.of(context)?.settings.arguments;
      Map map = arguments as Map;
      setState(() {
        if (map['diary'] != null) {
          _diaryModel = map['diary'];
          diaryDate = _diaryModel.diaryTime!;
          selectedDay = DateTime.parse(diaryDate); // 将字符串转换为DateTime对象
        } else {
          selectedDay = map['selectedDay'];
          diaryDate = DateFormat('yyyy-MM-dd').format(selectedDay!);
        }
        _titleController.text = _diaryModel.title!;
        _contentController.text = _diaryModel.content!;
      });
    });
  }

  @override
  void dispose() {
    //将要销毁的方法或数据放在这里
    super.dispose();

    _titleController.dispose();
    _contentController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        BrnLocalizationDelegate.delegate,
      ],
      // 应用支持的语言列表
      supportedLocales: S.delegate.supportedLocales,
      color: Colors.blue,
      home: Scaffold(
          body: ListView(
        children: [
          BrnNormalFormGroup(
            title: _diaryModel.diaryId == null ? "新增日记" : "编辑日记",
            children: [
              BrnTextInputFormItem(
                controller: _titleController,
                title: "标题",
                hint: "请输入标题",
                isRequire: true,
                onChanged: (newValue) {
                  _diaryModel.title = newValue;
                },
              ),
              BrnTextSelectFormItem(
                title: "时间",
                label: '请选择',
                value: diaryDate,
                isRequire: true,
                onTap: () {
                  BrnDatePicker.showDatePicker(context,
                      maxDateTime: DateTime.parse('2083-01-15'),
                      minDateTime: DateTime.parse('2024-01-01'),
                      initialDateTime: selectedDay,
                      // 支持DateTimePickerMode.date、DateTimePickerMode.datetime、DateTimePickerMode.time
                      pickerMode: BrnDateTimePickerMode.date,
                      pickerTitleConfig: BrnPickerTitleConfig.Default,
                      dateFormat: 'yyyy年,MM月,dd日', onConfirm: (dateTime, list) {
                    setState(() {
                      _diaryModel.diaryTime =
                          DateFormat("yyyy-MM-dd").format(dateTime);
                      selectedDay = dateTime;
                      diaryDate = DateFormat('yyyy-MM-dd').format(dateTime);
                    });
                  });
                },
              ),
              BrnTextBlockInputFormItem(
                controller: _contentController,
                title: "内容",
                hint: "请输入内容",
                isRequire: true,
                minLines: 1,
                maxLines: 5,
                onChanged: (newValue) {
                  setState(() {
                    _diaryModel.content = newValue;
                  });
                },
              ),
              BrnBottomButtonPanel(
                mainButtonName: '提交',
                mainButtonOnTap: () {
                  _saveOrUpdateDiary(_diaryModel.toJson()).then((value) {
                    BrnToast.show(
                        value!.msgModel.msg ?? '操作异常，请联系管理员', context);
                    if (value.msgModel.code == 200) {
                      Navigator.pop(context, value.msgModel);
                    }
                  });
                },
              )
            ],
          ),
        ],
      )),
    );
  }

  Future<MsgEntity?> _saveOrUpdateDiary(Map<String, dynamic> map) async {
    return await DiarySaveOrUpdateDao.fetch(map);
  }

  void _getDiaryDetail(int? diaryId) async {
    DiaryEntity? entity = await DiaryDetailDao.fetch(diaryId);
    setState(() {
      _diaryModel = entity!.diaryModel;
    });
  }
}
